<?php
namespace App\Models;

use App\Config\Database;
use PDO;
use PDOException;

/**
 * 群成员模型
 * @package App\Models
 * @description:
 * 1. 添加群成员
 * 2. 移除群成员
 * 3. 更新成员信息
 * 4. 获取群成员列表
 * 5. 检查用户是否在群内
 */
class GroupMember {
    private $conn;
    private $table = 'group_members';

    public $id;
    public $group_id;
    public $user_id;
    public $role;
    public $join_time;
    public $nickname_in_group;
    public $is_muted;
    public $exit_time;

    public function __construct() {
        $database = new Database();
        $this->conn = $database->getConnection();
    }

    /**
     * 添加成员到群组
     * @return bool
     */
    public function addMember() {
        try {
            $query = "INSERT INTO " . $this->table . " 
                (group_id, user_id, role, nickname_in_group, is_muted) 
                VALUES 
                (:group_id, :user_id, :role, :nickname_in_group, :is_muted)";
            
            $stmt = $this->conn->prepare($query);
            
            // 绑定参数
            $stmt->bindParam(':group_id', $this->group_id);
            $stmt->bindParam(':user_id', $this->user_id);
            $stmt->bindParam(':role', $this->role);
            $stmt->bindParam(':nickname_in_group', $this->nickname_in_group);
            $stmt->bindParam(':is_muted', $this->is_muted);
            
            // 设置默认值
            if ($this->role === null) $this->role = 1; // 默认普通成员
            if ($this->is_muted === null) $this->is_muted = 0;
            
            return $stmt->execute();
        } catch (PDOException $e) {
            // 唯一键冲突（uk_group_user）表示已存在
            if ($e->getCode() == 23000) {
                return $this->updateMemberStatus($this->group_id, $this->user_id, 1, null);
            }
            error_log("Add group member error: " . $e->getMessage());
            return false;
        }
    }

    /**
     * 从群组移除成员
     * @param int $groupId 群组ID
     * @param int $userId 用户ID
     * @return bool
     */
    public function removeMember($groupId, $userId) {
        try {
            $query = "UPDATE " . $this->table . " 
                      SET exit_time = CURRENT_TIMESTAMP 
                      WHERE group_id = :group_id AND user_id = :user_id";
            
            $stmt = $this->conn->prepare($query);
            $stmt->bindParam(':group_id', $groupId);
            $stmt->bindParam(':user_id', $userId);
            
            return $stmt->execute();
        } catch (PDOException $e) {
            error_log("Remove group member error: " . $e->getMessage());
            return false;
        }
    }

    /**
     * 更新成员信息（角色、昵称、禁言状态）
     * @return bool
     */
    public function updateMember() {
        try {
            $query = "UPDATE " . $this->table . " 
                      SET role = :role, 
                          nickname_in_group = :nickname_in_group,
                          is_muted = :is_muted
                      WHERE group_id = :group_id AND user_id = :user_id";
            
            $stmt = $this->conn->prepare($query);
            
            // 绑定参数
            $stmt->bindParam(':group_id', $this->group_id);
            $stmt->bindParam(':user_id', $this->user_id);
            $stmt->bindParam(':role', $this->role);
            $stmt->bindParam(':nickname_in_group', $this->nickname_in_group);
            $stmt->bindParam(':is_muted', $this->is_muted);
            
            return $stmt->execute();
        } catch (PDOException $e) {
            error_log("Update group member error: " . $e->getMessage());
            return false;
        }
    }

    /**
     * 更新成员状态（如退出时间）
     * @param int $groupId 群组ID
     * @param int $userId 用户ID
     * @param int $status 1表示在群内，0表示已退出
     * @param string|null $exitTime 退出时间
     * @return bool
     */
    public function updateMemberStatus($groupId, $userId, $status, $exitTime = null) {
        try {
            if ($status == 1) {
                $query = "UPDATE " . $this->table . " 
                          SET exit_time = NULL 
                          WHERE group_id = :group_id AND user_id = :user_id";
            } else {
                $query = "UPDATE " . $this->table . " 
                          SET exit_time = :exit_time 
                          WHERE group_id = :group_id AND user_id = :user_id";
            }
            
            $stmt = $this->conn->prepare($query);
            $stmt->bindParam(':group_id', $groupId);
            $stmt->bindParam(':user_id', $userId);
            
            if ($status == 0) {
                $exitTime = $exitTime ?: date('Y-m-d H:i:s');
                $stmt->bindParam(':exit_time', $exitTime);
            }
            
            return $stmt->execute();
        } catch (PDOException $e) {
            error_log("Update member status error: " . $e->getMessage());
            return false;
        }
    }

    /**
     * 获取群组成员列表
     * @param int $groupId 群组ID
     * @param int $page 页码
     * @param int $pageSize 每页数量
     * @return array
     */
    public function getMembers($groupId, $page = 1, $pageSize = 20) {
        try {
            $offset = ($page - 1) * $pageSize;
            
            $query = "SELECT gm.*, u.username, u.avatar_url 
                      FROM " . $this->table . " gm
                      JOIN users u ON gm.user_id = u.id
                      WHERE gm.group_id = :group_id AND gm.exit_time IS NULL
                      ORDER BY 
                          CASE WHEN gm.role = 3 THEN 0 
                               WHEN gm.role = 2 THEN 1 
                               ELSE 2 END,
                          gm.join_time
                      LIMIT :offset, :limit";
            
            $stmt = $this->conn->prepare($query);
            $stmt->bindParam(':group_id', $groupId);
            $stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
            $stmt->bindParam(':limit', $pageSize, PDO::PARAM_INT);
            
            $stmt->execute();
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            error_log("Get group members error: " . $e->getMessage());
            return [];
        }
    }

    /**
     * 检查用户是否在群内
     * @param int $groupId 群组ID
     * @param int $userId 用户ID
     * @return bool
     */
    public function isMember($groupId, $userId) {
        try {
            $query = "SELECT COUNT(*) as count 
                      FROM " . $this->table . " 
                      WHERE group_id = :group_id 
                      AND user_id = :user_id 
                      AND exit_time IS NULL";
            
            $stmt = $this->conn->prepare($query);
            $stmt->bindParam(':group_id', $groupId);
            $stmt->bindParam(':user_id', $userId);
            $stmt->execute();
            
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            return $result['count'] > 0;
        } catch (PDOException $e) {
            error_log("Check group membership error: " . $e->getMessage());
            return false;
        }
    }

    /**
     * 获取用户加入的群组列表
     * @param int $userId 用户ID
     * @return array
     */
    public function getUserGroups($userId) {
        try {
            $query = "SELECT g.* 
                      FROM " . $this->table . " gm
                      JOIN groups g ON gm.group_id = g.id
                      WHERE gm.user_id = :user_id AND gm.exit_time IS NULL
                      ORDER BY gm.join_time DESC";
            
            $stmt = $this->conn->prepare($query);
            $stmt->bindParam(':user_id', $userId);
            $stmt->execute();
            
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            error_log("Get user groups error: " . $e->getMessage());
            return [];
        }
    }
}